package com.leyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.dto.PageDTO;
import com.leyou.mapper.BrandMapper;
import com.leyou.mapper.CategoryMapper;
import com.leyou.pojo.Brand;
import com.leyou.pojo.Category;
import com.leyou.pojo.CategoryBrand;
import com.leyou.service.BrandService;
import com.leyou.service.CategoryBrandService;
import com.leyou.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author jshstart
 * @creat 2020-12-09 17:21
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {
    @Autowired
    private CategoryBrandService categoryBrandService;

    /**
     * 分页查询所有的品牌
     * @param key
     * @param brandPage
     * @return
     */
    @Override
    public PageDTO<Brand> queryBrandByPage(String key, Page<Brand> brandPage) {
        boolean empty = StringUtils.isEmpty(key);
        Page<Brand> page;
        if (empty){
              page = query().page(brandPage);
        }else {
              page = query().like("name", key)
                    .or()
                    .eq("letter", key)
                    .page(brandPage);
        }
        List<Brand> records = page.getRecords();
        long total = page.getTotal();
        int totalPage= (int) page.getPages();
        return new PageDTO<Brand>(total, (long) totalPage,records);
    }

    /**
     * 删除对应的品牌
     * @param id
     */
    @Transactional
    @Override
    public void deleteById(Long id) {
        QueryWrapper<CategoryBrand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id",id);
        CategoryBrand brand = categoryBrandService.getOne(queryWrapper);
        if (brand!=null&&"".equals(brand)){
            categoryBrandService.remove(queryWrapper);
        }
        this.removeById(id);
    }
}
